<template>
<div class="">
  <div class="info-title">运动员管理</div>
<el-card class="full-height full-width">
  <search-table class="full-height full-width"
    :table-loading="loading"
    :tableData="tableData"
    :ref="tableRef"
    :labelWidth="'40px'"
    :row-keys="row => row.id"
    @query="currentPage = 1; query();"
    @reset="doReset"
    @selectionChange="selectionChange">
    <template v-slot:row>
      <el-row :gutter="20">
        <el-col :span="8">
          <el-form-item label="名称">
            <el-input placeholder="请输入内容" v-model="searchForm.name" clearable></el-input>
          </el-form-item>
        </el-col>
        <el-col :span="8">
          <el-form-item label="电话">
            <el-input placeholder="请输入内容" v-model="searchForm.tel" clearable></el-input>
          </el-form-item>
        </el-col>
        <el-col :span="8">
          <el-form-item label="性别">
            <el-select placeholder="请选择" v-model="searchForm.sex" clearable>
              <el-option :label="'男'" :value="1"></el-option>
              <el-option :label="'女'" :value="2"></el-option>
            </el-select>
          </el-form-item>
        </el-col>
      </el-row>
    </template>
    <template v-slot:actions>
      <el-button size="small" type="primary" v-on:click="addAthlete()">新 建</el-button>
      <el-button size="small" type="primary" v-on:click="editAthlete()">编 辑</el-button>
      <el-button size="small" type="primary" v-on:click="handlerDelete()">删除/批量删除</el-button>
      <el-button size="small" type="primary" v-on:click="downloadTemplate()">下载模板</el-button>
      <el-button size="small" type="primary" v-on:click="importAthlete()">导入数据</el-button>
      <!-- <el-upload
        class="upload-demo"
        action="#"
        ref="atheletUpload"
        :limit = "1"
        :http-request="
        (file) => {
          return clickUp(file);
        }"
        :auto-upload="false"
        :beforeUpload="beforeUploadAthlete">
      </el-upload> -->
    </template>
    <template >
      <el-table-column :reserve-selection="true" type="selection" width="55" />
      <el-table-column prop="name" label="姓名" width="100" show-overflow-tooltip />
      <el-table-column prop="sex" label="性别" width="50" show-overflow-tooltip />
      <el-table-column prop="age" label="年龄" width="50" show-overflow-tooltip />
      <el-table-column prop="tel" label="电话" width="100" show-overflow-tooltip />
      <el-table-column prop="idCard" label="身份证" width="150" show-overflow-tooltip />
      <el-table-column prop="province" label="省份" show-overflow-tooltip />
      <el-table-column prop="unit" label="单位" show-overflow-tooltip />
      <el-table-column prop="applyStatus" label="状态" show-overflow-tooltip /> 
      <el-table-column label="操作" width="150">
        <template slot-scope="scope">
          <el-button
            v-if="scope.row.applyStatus === '待通过'"
            size="mini"
            type="success"
            @click="handleAgree(scope.$index, scope.row)">同意</el-button>
          <el-button
            v-if="scope.row.applyStatus === '待通过'"
            size="mini"
            type="danger"
            @click="handleDisAgree(scope.$index, scope.row)">拒绝</el-button>
        </template>
      </el-table-column>
    </template>
    <template v-slot:footer>
      <el-pagination
        background
        :current-page="currentPage"
        :page-sizes="pageSizes"
        :page-size="pageSize"
        layout="total, sizes, prev, pager, next, jumper"
        :total="total"
        @size-change="handleSizeChange"
        @current-change="handleCurrentChange" />
    </template>
  </search-table>
  <el-dialog  :close-on-click-modal="false" title="修改运动员" :visible.sync="dialogFormEdit">
    <el-form id="athlete"  ref="athlete" :model="athlete" :rules="rules" label-width="100px" >
      <el-form-item label="运动员姓名" prop="name">
        <el-col :span="8">
          <el-input v-model="athlete.name" auto-complete="off" ></el-input>
        </el-col>
      </el-form-item>
      <el-form-item>
        <el-col :span="12">
          <template>
            <el-radio v-model="radio" label="1">身份证</el-radio>
            <el-radio v-model="radio" label="2">其他证件</el-radio>
          </template>
        </el-col>
      </el-form-item>
      <el-form-item :label="cardType" prop="idCard">
        <el-col :span="12">
          <el-input @input="go" v-model="athlete.idCard" auto-complete="off"></el-input>
        </el-col>
      </el-form-item>
      <el-form-item v-if="this.user.roleKey =='jiazhang'" label="队伍编号" >
        <el-col :span="8">
          <el-input v-model="athlete.teamId" auto-complete="off" ></el-input>
        </el-col>
      </el-form-item>
      <el-form-item label="运动员电话" prop="tel">
        <el-col :span="8">
          <el-input v-model="athlete.tel" auto-complete="off"></el-input>
        </el-col>
      </el-form-item>
      <el-form-item label="运动员性别" prop="sex">
        <el-col :span="8">
          <el-input :disabled="athleteAge" v-model="athlete.sex" ></el-input>
          <!-- <el-select v-model="athlete.sex" value-key="id">
            <el-option v-for="item in sexArry"  :key="item.id" :label="item.name" :value="item.name"></el-option>
          </el-select> -->
        </el-col>
      </el-form-item>
      <el-form-item label="运动员年龄" prop="age">
        <el-col :span="8">
          <el-input :disabled="athleteAge" v-model="athlete.age"></el-input>
        </el-col>
      </el-form-item>
      <el-form-item label="运动员备注" >
        <el-col :span="14">
          <el-input v-model="athlete.note" auto-complete="off" type="textarea" :rows="2" />
        </el-col>
      </el-form-item>
      <el-form-item label="所在地区" >
        <el-col :span="8">
          <el-input v-model="athlete.province" auto-complete="off" :rows="2" />
          <!-- <el-select v-model="athlete.levelId" value-key="id">
            <el-option v-for="item in levelArray"  :key="item.id" :label="item.name" :value="item.id"></el-option>
          </el-select> -->
        </el-col>
      </el-form-item>
      <el-form-item label="单位" >
        <el-col :span="8">
          <el-input v-model="athlete.unit" auto-complete="off" :rows="2" />
        </el-col>
      </el-form-item>
    </el-form>
    <div slot="footer" class="dialog-footer">
      <el-button @click="dialogFormEdit = false">取 消</el-button>
      <el-button type="primary" @click="edit(athlete)">确 定</el-button>
    </div>
  </el-dialog>
  <el-dialog  :close-on-click-modal="false" title="添加运动员" :visible.sync="dialogFormAdd">
    <el-form id="athlete"  ref="athlete" :model="athlete" :rules="rules" label-width="100px" >
      <el-form-item label="运动员姓名" prop="name">
        <el-col :span="8">
          <el-input v-model="athlete.name" auto-complete="off" ></el-input>
        </el-col>
      </el-form-item>
      <el-form-item>
        <el-col :span="12">
          <template>
            <el-radio v-model="radio" label="1">身份证</el-radio>
            <el-radio v-model="radio" label="2">其他证件</el-radio>
          </template>
        </el-col>
      </el-form-item>
      <el-form-item :label="cardType" prop="idCard">
        <el-col :span="12">
          <el-input @input="go" v-model="athlete.idCard" auto-complete="off"></el-input>
        </el-col>
      </el-form-item>
      <el-form-item v-if="this.user.roleKey =='jiazhang'" label="队伍编号" >
        <el-col :span="8">
          <el-input v-model="athlete.teamId" auto-complete="off" ></el-input>
        </el-col>
      </el-form-item>
      <el-form-item label="运动员电话" prop="tel">
        <el-col :span="8">
          <el-input v-model="athlete.tel" auto-complete="off"></el-input>
        </el-col>
      </el-form-item>
      <el-form-item label="运动员性别" prop="sex">
        <el-col :span="8">
          <el-input :disabled="athleteAge" v-model="athlete.sex"></el-input>
          <!-- <el-select v-model="athlete.sex" value-key="id">
            <el-option v-for="item in sexArry"  :key="item.id" :label="item.name" :value="item.name"></el-option>
          </el-select> -->
        </el-col>
      </el-form-item>
      <el-form-item label="运动员年龄" prop="age">
        <el-col :span="8">
          <el-input :disabled="athleteAge" v-model="athlete.age"></el-input>
        </el-col>
      </el-form-item>
      <el-form-item label="运动员备注" >
        <el-col :span="14">
          <el-input v-model="athlete.note" auto-complete="off" type="textarea" :rows="2" />
        </el-col>
      </el-form-item>
      <el-form-item label="所在地区" >
        <el-col :span="8">
          <el-input v-model="athlete.province" auto-complete="off" :rows="2" />
          <!-- <el-select v-model="athlete.levelId" value-key="id">
            <el-option v-for="item in levelArray"  :key="item.id" :label="item.name" :value="item.id"></el-option>
          </el-select> -->
        </el-col>
      </el-form-item>
      <el-form-item label="单位" >
        <el-col :span="8">
          <el-input v-model="athlete.unit" auto-complete="off" :rows="2" />
        </el-col>
      </el-form-item>
    </el-form>
    <div slot="footer" class="dialog-footer">
      <el-button @click="dialogFormAdd = false">取 消</el-button>
      <el-button type="primary" @click="add(athlete)">确 定</el-button>
    </div>
  </el-dialog>
  <el-dialog  :close-on-click-modal="false" title="导入excel" v-if="dialogVisible" :visible.sync="dialogVisible" width="40%">
    <el-upload
      class="ml-10"
      :limit="limitNum"
      :auto-upload="false"
      accept=".xlsx"
      :action="UploadUrl()"
      :before-upload="beforeUploadFile"
      :on-change="fileChange"
      :on-exceed="exceedFile"
      :on-success="handleSuccess"
      :on-error="handleError"
      :file-list="fileList"
    >
      <el-button slot="trigger" size="small" type="primary">导入运动员</el-button>
      <!-- <div class="el-upload__text">将文件拖到此处，或<em>点击上传</em></div> -->
      <div class="el-upload__tip" slot="tip">只能上传xlsx文件，且不超过10M</div>
    </el-upload>
    <span slot="footer" class="dialog-footer">
      <el-button @click="dialogVisible = false">取 消</el-button>
      <el-button type="primary" @click="uploadFile">确 定</el-button>
    </span>
  </el-dialog>
  </el-card>
</div>
</template>

<script>
import { mapState } from 'vuex'
import searchTable from '@/components/PublicTable/index.vue'
import {getAthleteList, batchDelete, insert, getById, update, agreeJoin,downloadtemplate,uploadAthlete} from "@/api/athlete";
import { Message} from "element-ui";
// import { download } from '@/utils/request';
// import {getLevelList} from "@/api/level";
// import {getList} from "@/api/state";
// import {getUserList} from "@/api/user";

export default{
  components:{
    searchTable
  },
  data () {
    return {
      radio: '1',
      athleteAge: true,
      cardType:'身份证',
      limitNum: 1,  // 上传excell时，同时允许上传的最大数
      fileList: [],   // excel文件列表
      dialogVisible:false,
      tableData: [],
      loading: false,
      tableRef: 'tableRef',
      searchForm: {},
      currentPage: 1,
      pageSizes: [10, 20, 50],
      pageSize: 20,
      total: 0,
      selectionList:[], //定义删除/批量删除
      dialogFormAdd:false,
      dialogFormEdit: false,
      athlete:{
        id:'',
        name:'',
        sex:'',
        // levelId:'',
        province:'',
        note:'',
        applyStatus:'',
        state:'',
        unit:'',
        tel:'',
        userId:'',
        idCard:'',
        age:'',
        teamId:''
      },
      sexArry:[
        {
          "id": 1,
          "name": "男"
        },
        {
          "id": 2,
          "name": "女"
        }
      ],
      levelArray:[],
      stateArray:[
        {
          "id": 1,
          "name": "显示"
        },
        {
          "id": 2,
          "name": "隐藏"
        }
      ],
      rules:{
        name:[
          {
            required:true,message:'请填写姓名', trigger: 'blur'
          },
          {
            validator: function(rule, value, callback) {
              let name = /^[\u4E00-\u9FA5]{2,10}(·[\u4E00-\u9FA5]{2,10}){0,2}$/
              if (!name.test(value)) {
                callback(
                  new Error('请输入汉字(2-10)位')
                )
              } else {
                callback()
              }
            },
            trigger: 'blur'
          }
        ],
        sex:[
          {
            required: true, message: '请选择性别', trigger: 'change'
          }
        ],
        age:[
          {
            required: true, message: '年龄', trigger: 'change'
          }
        ],
        tel:[
          {
            required:true,message:'请填写电话', trigger: 'blur'
          },
          {
            validator: function(rule, value, callback) {
              let phone = /^((13[0-9])|(14[5,7])|(15[0-3,5-9])|(17[0,3,5-8])|(18[0-9])|166|198|199|(147))\d{8}$/
              if (!phone.test(value)) {
                callback(
                  new Error('请输入正确手机号')
                )
              } else {
                callback()
              }
            },
            trigger: 'blur'
          }
        ],
        idCard:[
          {
            required:true,message:'请填写身份证号', trigger: 'blur'
          },
          {
            validator: function(rule, value, callback) {
              let card = /^[1-9]\d{5}(18|19|([23]\d))\d{2}((0[1-9])|(10|11|12))(([0-2][1-9])|10|20|30|31)\d{3}[0-9Xx]$/
              if(this.athleteAge == true) {
                if (!card.test(value)) {
                  callback(
                    new Error('请输入正确身份证号')
                  )
                } else {
                  callback()
                }
              } else {
                callback()
              }          
            },
            trigger: 'blur'
          }
        ]
      }
    };
  },
  created() {
    this.query()
    this.getTeamId()
  },
  watch: {
    radio(newVal,oldVal){
      if(newVal == '1') {
        this.cardType = '身份证'
        this.athleteAge = true
      } else {
        this.cardType = '其他证件'
        this.athleteAge = false
      }
      
    }
  },
  computed:{
    ...mapState({
      user:state => state.user.userInfo
    })
  },
  methods: {
    // 计算年龄性别
    go() {
      // let val = '370283199204140053'
      // console.log('go',val)
      if(this.athleteAge == true) {
        let iden = this.athlete.idCard;
        let sex = null;
        let birth = null;
        let myDate = new Date();
        let month = myDate.getMonth() + 1;
        let day = myDate.getDate();
        let age = 0;
        if (iden.length === 18) {
          age = myDate.getFullYear() - iden.substring(6, 10) - 1;
          sex = iden.substring(16, 17);
          birth =
            iden.substring(6, 10) +
            "-" +
            iden.substring(10, 12) +
            "-" +
            iden.substring(12, 14);
          if (
            iden.substring(10, 12) < month ||
            (iden.substring(10, 12) == month && iden.substring(12, 14) <= day)
          )
            age++;
        }
        if (iden.length === 15) {
          age = myDate.getFullYear() - iden.substring(6, 8) - 1901;
          sex = iden.substring(13, 14);
          birth =
            "19" +
            iden.substring(6, 8) +
            "-" +
            iden.substring(8, 10) +
            "-" +
            iden.substring(10, 12);
          if (
            iden.substring(8, 10) < month ||
            (iden.substring(8, 10) == month && iden.substring(10, 12) <= day)
          )
            age++;
        }
        if (sex % 2 === 0) sex = '女';
        else sex = '男';
        //性别  ==> 0:男       1:女
        // 性别
        this.athlete.sex = sex;
        // 出生日期
        // this.formData.birthdate = birth;
        // 年龄
        this.athlete.age = age;

        // console.log(this.athlete,'xxx')
      }else {
        return 
      }
    },
    // 下载模板
    downloadTemplate() {
      downloadtemplate().then(res => {
        const link = document.createElement('a');
        let blob = new Blob([res], { type: 'application/vnd.openxmlformats-officedocument.spreadsheetml.sheet;charset=UTF-8' });
        let objectUrl = window.URL.createObjectURL(blob);
        link.href = objectUrl;
        link.download = 'Excel模板';
        const elementA = document.querySelector('.view-container');
        link.style.display = 'none';
        elementA?.append(link);
        link.click();
        elementA?.removeChild(link);
        window.URL.revokeObjectURL(link.href);
      })
    },
    UploadUrl() {
      // 因为action参数是必填项，我们使用二次确认进行文件上传时，直接填上传文件的url会因为没有参数导致api报404，所以这里将action设置为一个返回为空的方法就行，避免抛错
      return "";
    },
    // 文件超出个数限制时的钩子
    exceedFile(files, fileList) {
      this.$message.warning(
        `只能选择 ${this.limitNum} 个文件，当前共选择了 ${files.length +
          fileList.length} 个`
      );
    },
    // 文件状态改变时的钩子
    fileChange(file, fileList) {
      console.log(file.raw);
      this.fileList.push(file.raw);
      console.log(this.fileList);
    },
    // 上传文件之前的钩子, 参数为上传的文件,若返回 false 或者返回 Promise 且被 reject，则停止上传
    beforeUploadFile(file) {
      console.log("before upload");
      console.log(file);
      let extension = file.name.substring(file.name.lastIndexOf(".") + 1);
      let size = file.size / 1024 / 1024;
      if (extension !== "xlsx") {
        this.$message.warning("只能上传后缀是.xlsx的文件");
      }
      if (size > 10) {
        this.$message.warning("文件大小不得超过10M");
      }
    },
    // 文件上传成功时的钩子
    handleSuccess(res, file, fileList) {
      this.$message.success("文件上传成功");
    },
    // 文件上传失败时的钩子
    handleError(err, file, fileList) {
      this.$message.error("文件上传失败");
    },
    uploadFile() {
      if (this.fileList.length === 0) {
        this.$message.warning("请上传文件");
      } else {
        let form = new FormData();
        form.append("file", this.fileList[0]);
        uploadAthlete(form).then(res => {
        if (res.code == 200) {
          this.$message({
            type: "success",
            message: "上传成功",
          });
          this.query()
          this.dialogVisible = false
        } else {
          this.$message({
            type: "error",
            message: "上传失败",
          });
          this.dialogVisible = false
        }
      })
        this.fileList = [];
      }
    },
    // 导入运动员数据
    importAthlete() {
      this.dialogVisible = true
    },
    getTeamId() {
      this.athlete.teamId = this.user.teamId
    },
    beforeUploadAthlete(file) {
      const extension = file.name.split(".")[1] === "xls";
      const extension2 = file.name.split(".")[1] === "xlsx";
      const isLt2M = file.size / 1024 / 1024 < 10;
      if (!extension && !extension2) {
        this.$message({
          message: '上传模板只能是 xls、xlsx格式!',
          type: 'error'
        });
        return false // return false就不会走上传接口
      }
      if (!isLt2M) {
        console.log("上传模板大小不能超过 10MB!");
        this.$message({
          message: '上传模板大小不能超过 10MB!',
          type: 'error'
        });
        return false
      }
      // return extension || extension2 || extension3 || (extension4 && isLt2M);
      return extension || extension2 // 必须要有返回值
    },
    upload(file) {
      const formData = new FormData();
      formData.append("file", file.file);
      console.log(formData,file)
      // uploadAthlete(formData).then(res => {
      //   if (res.code == 200) {
      //     this.$message({
      //       type: "success",
      //       message: "上传成功",
      //     });
      //     // this.costDialog = false
      //   } else {
      //     this.$message({
      //       type: "error",
      //       message: "上传失败",
      //     });
      //     // this.costDialog = false
      //   }
      // })
    },
    query() {
      // 请求表格数据
      var params ={
        'pageNum': this.currentPage,
        'pageSize': this.pageSize,
        'name':this.searchForm.name,
        'tel':this.searchForm.tel,
        'sex':this.searchForm.sex
      }
      getAthleteList(params).then(res => {
        
        // 把请求到的数据给testDatas数组
        this.tableData = res.data.list
        // 当前页数
        this.currentPage = res.data.currPage
        // 当前页数量
        this.pageSize = res.data.pageSize
        // 分页总数
        this.total = res.data.totalCount
      //   console.log(JSON.stringify(res.data.data.total))
      })
      .catch((error) => {
        console.log(error)
      })
    },
    doReset() {
      // 重置搜索条件
      // 请求表格数据
      this.tableData = [];
      this.restForm();
      this.query();
    },
    restForm(){
      this.searchForm.name = ""
      this.searchForm.tel = ""
      this.searchForm.sex = ""
    },
    selectionChange(val) {
      this.selectionList = []
      val.forEach(element => {
        this.selectionList.push(element.id)
      });
    },
    handlerDelete(){
      // 数组转字符串使用逗号分隔
      let ids =  this.selectionList.join(",")
      console.log(ids)
      var params ={
          'ids': ids
      }
      batchDelete(params).then(res =>{
        Message({
          message: '批量删除成功',
          type: 'success',
          duration: 3 * 1000
        })
        // 重新查询表格
        this.query()
      }).catch((error) => {
        console.log(error)
      })
    },
    // 同意入队
    handleAgree(index, row) {
      let id = row.id
      let params ={
          'id': id,
          'result':'yes'
      }
      agreeJoin(params).then(res => {
        Message({
          message: '入队通过',
          type: 'success',
          duration: 3 * 1000
        })
        // 重新查询表格
        this.query()
      }).catch((error) => {
        console.log(error)
      })
    },
    // 拒绝入队
    handleDisAgree(index, row) {
      let id = row.id
      console.log(row)
      let params ={
          'id': id,
          'result':'no'
      }
      agreeJoin(params).then(res => {
        Message({
          message: '拒绝入队',
          type: 'success',
          duration: 3 * 1000
        })
        // 重新查询表格
        this.query()
      }).catch((error) => {
        console.log(error)
      })
    },
    handleSizeChange(val) {
      // 改变每页条数
      this.pageSize = val
      this.query()
    },
    handleCurrentChange(val) {
      // 切换页码
      this.currentPage = val
      this.query()
    },
    // table 数据转换
    formatSexType(row, column){
      if(row.sex === '1'){
          return '男'
      } else if(row.sex === '2') {
          return '女'
      } else {
          return ''
      }
    },
    // 新增运动员
    addAthlete(){
      this.athlete = {}
      this.athlete.teamId = this.user.teamId
      this.dialogFormAdd = true
    },
    // 修改运动员
    editAthlete(){
      // console.log('下标', index)
      // console.log('数据', row)
      // console.log(this.selectionList)
      // console.log(typeof(this.selectionList))
      let id = this.selectionList[0]
        var params = {
          'id' : id
        }
      getById(params).then(res =>{
        this.athlete = {}
        this.athlete = res.data
        this.dialogFormEdit = true
      }).catch((error) => {
          console.log(error)
      })
    },
    add(athlete){
      console.log(this.$refs.athlete.validate,'666',athlete)
      this.$refs.athlete.validate(valid => {
        if(valid) {
          insert(athlete).then(res =>{
            Message({
              message: '运动员新增成功',
              type: 'success',
              duration: 3 * 1000
            })
            // 新增弹出框隐藏
            this.dialogFormAdd = false
            // 重新查询表格
            this.query()
          }).catch((error) => {
            console.log(error)
          })
        } else {
          console.log('fail')
        }
      })
      
    },
    edit(athlete){
      this.$refs.athlete.validate(valid => {
        if(valid) {
          update(athlete).then(res =>{
            Message({
              message: '运动员修改成功',
              type: 'success',
              duration: 3 * 1000
            })
            // 新增弹出框隐藏
            this.dialogFormEdit = false
            // 重新查询表格
            this.query()
          }).catch((error) => {
            console.log(error)
          })
        } else {
          console.log('fail')
        }
      })
      
    }
  }
}
</script>
<style>
.info-title {
  font-size: 18px;
  font-weight: bold;
  margin-bottom: 20px;
}
</style>